﻿using mBook.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;


namespace mBook.DataManager
{
    public class RESTfulService
    {
        #region HTTP Methods

        /// <summary>
        /// [nhbao]
        /// Get a JSON object using HTTP GET request
        /// </summary>
        /// <param name="url">Webservice url</param>
        /// <param name="expectedModel">Model type for JSON to parse to</param>
        /// <returns>JSON object</returns>
        public async static Task<object> HTTPGetRequest(string url, Type  expectedType)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                throw new NetworkException();
            }

            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
            }

            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(expectedType);
            object objResponse;
            try
            {
                objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return objResponse;
        }

        /// <summary>
        /// [nhbao]
        /// Post XML data using HTTP POST request
        /// </summary>
        /// <param name="url">Webservice url</param>
        /// <param name="postData">XML data to post</param>
        /// <param name="expectedModel">Model type for JSON to parse to</param>
        /// <returns>JSON object</returns>
        public async static Task<object> HTTPPostRequest(string url, string postData, Type expectedModel)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";

            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                throw new NetworkException();
            }

            using (Stream writeStream = await request.GetRequestStreamAsync())
            {
                if (postData != null && postData != string.Empty)
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(postData);
                    writeStream.Write(bytes, 0, bytes.Length);
                    
                }
            }

            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
            }

            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(expectedModel);
            object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());

            return objResponse;
        }

        #endregion
    }
}
